import { useDebounce, useUrlQueryParam } from "hooks";
import { useCallback, useMemo } from "react";
import { useLocation } from "react-router";
import { useProject } from "server";
import { useTask } from "server/useTask";

export const useProjectIdUrl = () => {
  const { pathname } = useLocation();
  const projectId = pathname.match(/project\/(\d+)/)?.[1];
  return Number(projectId);
};

export const useProjectInUrl = () => useProject(useProjectIdUrl());

export const useKanbanSearchParams = () => {
  const projectId = useProjectIdUrl();
  return { projectId };
};

export const useTasksSearchParams = () => {
  const [params] = useUrlQueryParam(["name", "typeId", "processorId", "tagId"]);
  const projectId = useProjectIdUrl();
  const debouncedNmae = useDebounce(params.name);
  return useMemo(
    () => ({
      projectId,
      typeId: Number(params.typeId) || undefined,
      processorId: Number(params.processorId) || undefined,
      tagId: Number(params.tagId) || undefined,
      name: debouncedNmae || undefined,
    }),
    [debouncedNmae, params.processorId, params.tagId, params.typeId, projectId]
  );
};

export const useKanbansQueryKey = () => ["kanbans", useKanbanSearchParams];

export const useTasksQueryKey = () => ["tasks", useTasksQueryKey];

export const useTasksModal = () => {
  const [{ editingTaskId }, setEditingTaskId] = useUrlQueryParam([
    "editingTaskId",
  ]);
  const { data: editingTask, isLoading } = useTask(Number(editingTaskId));

  const startEdit = useCallback(
    (id: number) => {
      setEditingTaskId({ editingTaskId: id });
    },
    [setEditingTaskId]
  );

  const close = useCallback(() => {
    setEditingTaskId({ editingTaskId: "" });
  }, [setEditingTaskId]);

  return {
    editingTaskId,
    editingTask,
    startEdit,
    close,
    isLoading,
  };
};
